package cn.gtv.sdk.dcas.api;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;

import com.sad.basic.utils.app.AppInfoUtil;
import com.sad.jetpack.v1.datamodel.api.GlobalDataModelConfig;
import com.sad.jetpack.v1.datamodel.api.IDataModelObtainedCallback;
import com.sad.jetpack.v1.datamodel.api.IDataModelRequest;
import com.sad.jetpack.v1.datamodel.api.IDataModelResponse;
import com.sad.jetpack.v1.datamodel.api.extension.interceptor.DefaultCacheLoader;

import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import cn.gtv.sdk.dcas.api.db.Event;

public final class DCASCore {

    public static final int BP_VERSION_CODE=2;

    protected static Context mContext=null;
    public static GlobalConfig globalConfig=null;
    private static boolean isObservedDCASDataStorage =false;
    public static GlobalConfig getGlobalConfig(){
        if (globalConfig==null){
            globalConfig=new GlobalConfig(mContext);
        }
        return globalConfig;
    }

    public static void startObserveDCASDataStorageObserver(boolean privacyAgree){
        if (privacyAgree && !isObservedDCASDataStorage){
            Observer<List<Event>> observer=new DefaultEventDataDBObserver(mContext,globalConfig.recorderStrategy);
            String currAppProcessName=AppInfoUtil.getCurrAppProccessName(mContext);
            if (mContext.getPackageName().equals(currAppProcessName)){
                //主进程下处理
                try {
                    if (!EventsManager.getInstance(mContext).getAllLiveData().hasObservers() && observer!=null){
                        //EventsManager.getInstance(mContext).getAllLiveData().observeForever(observer);
                        EventsManager.getInstance(mContext).observeAllLiveData(observer);
                        isObservedDCASDataStorage=true;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
    }

    public static void init(Context context,GlobalConfig config,boolean privacyAgree){
        if (privacyAgree){
            if (context!=null && mContext==null){
                mContext=context;
            }
            GlobalDataModelConfig.getInstance().enableLogUtils(true);
            globalConfig=config;
            if (mContext!=null){
                DefaultCacheLoader.initCacheLoader(mContext);
            }
        }

    }

    public static class GlobalConfig{
        private String submitApi="https://eventlog-api.gzstv.com/data-upload/submit-batch";
        private String encryptionKeyApi="https://eventlog-api.gzstv.com/data-upload/auth-pk";
        private IServerTokenFactory serverTokenFactory;
        private String serverAuthKeyV3="FpTx5RtXUftP4l-kTGtHKCCVS8vX86_tEkf7jgS1Ml8";
        private String serverAuthKeyV2="f@aix+xk7du0*dh$98-w";
        private String product="";
        private String client="APP";
        private Context context;

        private IDCASRecorderStrategy recorderStrategy=new IDCASRecorderStrategy() {
            @Override
            public boolean enableUpload(List<Event> events) {
                return events!=null && events.size()>=20;
            }

            @Override
            public boolean enableStorage(List<Event> events) {
                return events!=null && events.size()<5000;
            }
        };

        public GlobalConfig recorderStrategy(@NonNull IDCASRecorderStrategy recorderStrategy){
            if (recorderStrategy==null){
                return this;
            }
            this.recorderStrategy=recorderStrategy;
            return this;
        }

        public IDCASRecorderStrategy getRecorderStrategy() {
            return recorderStrategy;
        }

        public GlobalConfig(Context context){
            this.context=context;
        }

        /*public GlobalConfig maxCount(long max_count){
            this.max_count=max_count;
            return this;
        }

        public long getMax_count(){
            return max_count;
        }*/

        public GlobalConfig client(String client){
            this.client=client;
            return this;
        }
        public String getClient() {
            return client;
        }

        public GlobalConfig product(String product){
            this.product=product;
            return this;
        }
        public String getProduct() {
            return product;
        }

        public GlobalConfig serverTokenFactory(IServerTokenFactory serverTokenFactory){
            this.serverTokenFactory=serverTokenFactory;
            return this;
        }

        public GlobalConfig serverAuthKeyV3(String serverAuthKeyV3){
            this.serverAuthKeyV3=serverAuthKeyV3;
            return this;
        }

        public IServerTokenFactory getServerTokenFactory() {
            return serverTokenFactory;
        }

        public String getServerAuthKeyV3() {
            return serverAuthKeyV3;
        }

        public GlobalConfig serverAuthKeyV2(String serverAuthKeyV2){
            this.serverAuthKeyV2=serverAuthKeyV2;
            return this;
        }

        public String getServerAuthKeyV2() {
            return serverAuthKeyV2;
        }

        public String getSubmitApi() {
            return submitApi;
        }

        public GlobalConfig submitApi(String submitApi) {
            this.submitApi = submitApi;
            return this;
        }

        public String getEncryptionKeyApi() {
            return encryptionKeyApi;
        }

        public GlobalConfig encryptionKeyApi(String encryptionKeyApi) {
            this.encryptionKeyApi = encryptionKeyApi;
            return this;
        }
    }

    public static void initNewEncryptionKey(Context context){
        HttpDCASObtainEncryptionKeyClient.newInstance(context)
                .url(getGlobalConfig().encryptionKeyApi/*"https://eventlog-api.gzstv.com/data-upload/auth-pk"*/)
                .method(IDataModelRequest.Method.POST)
                .log(true)
                .dataModelProducer("dcas_obtain_encryptionKey")
                .callback(new IDataModelObtainedCallback<String>() {
                    @Override
                    public void onDataObtainedCompleted(IDataModelResponse<String> response) {
                        String res=response.body();
                        if (!TextUtils.isEmpty(res)){
                            try {
                                JSONObject json=new JSONObject(res);
                                if (json.optBoolean("isSuccess")){
                                    String k= json.optString("result","");
                                    if (!TextUtils.isEmpty(k)){
                                        EncryptionKeyStorageManager.saveKey(context,k);
                                    }
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                })
                .execute();
    }


    public static boolean isUploading(Context context){
        SharedPreferences sharedPreferences=context.getSharedPreferences("DCAS",Context.MODE_MULTI_PROCESS|Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean("uploading",false);
    }

    public static void setUploading(Context context,boolean uploading){
        try {
            SharedPreferences sharedPreferences=context.getSharedPreferences("DCAS",Context.MODE_MULTI_PROCESS|Context.MODE_PRIVATE);
            sharedPreferences.edit().putBoolean("uploading",uploading).commit();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
